package com.collection;

import com.exception.DemoException;

import java.util.List;
import java.util.NoSuchElementException;

/**
 * ArrayList:底层实现是数组，所以查询快，修改、插入、删除慢
 * LinkedList:底层实现是链表。所以，查询慢。修改。插入、删除快
 *
 * @author jiangbang
 * @date 2016/5/27
 */
public class MyLinkedList /*implements List*/ {
    //有了第一个，和最后一个，中间的可以推出来
    private Node first;
    private Node last;

    private int size;

    public void add(Object obj) {
        Node n = new Node();
        if (first == null) {
            n.setPrevious(null);
            n.setObj(obj);
            n.setNext(null);

            first = n;
            last = n;
        } else {
            n.setPrevious(last);
            n.setObj(obj);
            n.setNext(null);
            last.setNext(n);
            last = n;
        }
        size++;
    }

    public int size() {
        return size;
    }

    public Object get(int index){  // 2
        //index越界处理
        if(index<0 || index>=size){
            try {
                throw new DemoException();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        //遍历需要先找到第一个数 0 1 2 3 4
        Node temp = null;
        if(first != null){
           temp = first; //从第一个开始遍历
            for(int i=0;i<index;i++){
                temp = temp.next;
            }
        }
        return temp;
    }

    public void remove(int index){
        //index越界处理
        if(index<0 || index>=size){
            try {
                throw new DemoException();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        //获取要删除的
        Node temp = null;
        if(first != null){
            temp = first; //从第一个开始遍历
            for(int i=0;i<index;i++){
                temp = temp.next;
            }
        }
        //将上一个和下一个直接相连
        if(temp !=null){
            Node up = temp.previous; //删除的上一个
            Node down = temp.next;  //删除的下一个
            up.next = down;
            down.previous = up;
            size--;
        }
    }

    public void add (int index,Object obj){
        //插入之前的节点
        Node temp = null;
        if(first != null){
            temp = first; //从第一个开始遍历
            for(int i=0;i<index;i++){
                temp = temp.next;
            }
        }

        Node newNode = new Node();
        newNode.Obj = obj;

        if(temp != null){
            Node up = temp.previous;
            up.next = newNode;
            newNode.previous = up;

            newNode.next = temp;
            temp.previous = newNode;

        }


    }

    public static void main(String[] args) {
        MyLinkedList linkedList = new MyLinkedList();
        linkedList.add("aaa");
        linkedList.add("bbb");
        linkedList.add("ccc");
        System.out.println(linkedList);
    }

}
